package com.heima.search.service.imp;


import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.dto.HistorySearchDto;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.common.thread.AppThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;


import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {
    @Autowired
    RestHighLevelClient restHighLevelClient;
    /**
     * es文章分页检索
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        //1.检查参数
        if (dto==null || StringUtils.isBlank(dto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = AppThreadLocalUtil.getUser();
        if (user != null && dto.getFromIndex()== 0){
            insert(dto.getSearchWords(), user.getId());
        }
        //2.设置查询条件
        SearchRequest request = new SearchRequest("app_info_article");
        SearchSourceBuilder sourcebuilder = new SearchSourceBuilder();
        //设置布尔查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //关键字的分词之后查询
        QueryStringQueryBuilder queryStringQueryBuilder = QueryBuilders.
                queryStringQuery(dto.getSearchWords()).field("title").field("content").
                defaultOperator(Operator.OR);
        boolQueryBuilder.must(queryStringQueryBuilder);
        //查询小于mindate的数据
        RangeQueryBuilder rangequery
                = QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime().getTime());
        boolQueryBuilder.filter(rangequery);
        //分页查询
        sourcebuilder.from(0);
        sourcebuilder.size(dto.getPageSize());
        //按照发布时间倒序
        sourcebuilder.sort("publishTime", SortOrder.DESC);
        //设置高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<font style='color: red; font-size: inherit;'>");
        highlightBuilder.postTags("</font>");
        sourcebuilder.highlighter(highlightBuilder);
        //将布尔查询条件封装到source
        sourcebuilder.query(boolQueryBuilder);
//        将所有查询，筛选的条件封装到request
        request.source(sourcebuilder);
//        es搜索
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);

        //3.结果封装返回
        ArrayList<Object> list = new ArrayList<>();
        SearchHit[] hits = response.getHits().getHits();
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            Map map = JSON.parseObject(json, Map.class);
            //处理高亮
            if (hit.getHighlightFields()!=null &&hit.getHighlightFields().size()>0){
                Text[] titles = hit.getHighlightFields().get("title").getFragments();
                String join = StringUtils.join(titles);
                //高亮标题
                map.put("h_title",join);
            }else {
                //原始标题
                map.put("h_title",map.get("title"));
            }
            list.add(map);
        }

        return ResponseResult.okResult(list);
    }

    /**
     * 添加历史记录到MongoDB
     * @param keyword
     * @param userId
     */
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    @Async
    public void insert(String keyword, Integer userId) {
        //1.查询当前用户的搜索关键词
        Query query = Query.query(Criteria.where("userId").is(userId).and("keyword").is(keyword));
        ApUserSearch apusersearch = mongoTemplate.findOne(query, ApUserSearch.class);
        //判断用户是否存在的逻辑
        if (apusersearch != null){
            apusersearch.setCreatedTime(new Date());
            mongoTemplate.save(apusersearch);
            return;
        }
        //不存在的话,先查询历史记录是否已经到了10条
        ApUserSearch newapUserSearch = new ApUserSearch();
        newapUserSearch.setUserId(userId);
        newapUserSearch.setKeyword(keyword);
        newapUserSearch.setCreatedTime(new Date());
        Query query1 = Query.query(Criteria.where("userId").is(userId));
        query1.with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApUserSearch> apusersearchlist = mongoTemplate.find(query1, ApUserSearch.class);
        //没有到10条
        if (apusersearchlist == null || apusersearchlist.size()<10){
            mongoTemplate.save(newapUserSearch);
        }else {
            ApUserSearch apUserSearch = apusersearchlist.get(apusersearchlist.size() - 1);
            mongoTemplate.findAndReplace(Query.query(Criteria.where("id").is(apUserSearch.getId())),newapUserSearch);
        }
    }

    @Override
    public ResponseResult findUserSearch() {
        //获取当前用户
        ApUser user = AppThreadLocalUtil.getUser();
        if(user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        List<ApUserSearch> apUserSearches = mongoTemplate.find(Query.query(Criteria.where("userId").is(user.getId())).with(Sort.by(Sort.Direction.DESC, "createdTime")), ApUserSearch.class);
        return ResponseResult.okResult(apUserSearches);
    }

    @Override
    public ResponseResult delUserSearch(HistorySearchDto historySearchDto) {
        //获取当前用户
        ApUser user = AppThreadLocalUtil.getUser();
        if(user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        mongoTemplate.remove(Query.query(Criteria.where("userId").is(user.getId()).and("id").is(historySearchDto.getId())), ApUserSearch.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
